package com.fengye.serialization.serializer.impl;

import com.fengye.serialization.serializer.Serializer;
import org.jboss.marshalling.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @Author fengye
 * @Date 2023/2/13 10:56
 **/
public class MarshallingSerializer implements Serializer {

    private final static MarshallingConfiguration configuration = new MarshallingConfiguration();

    private final static MarshallerFactory factory = Marshalling.getProvidedMarshallerFactory("serial");

    static {
        configuration.setVersion(5);
    }

    @Override
    public <T> byte[] serialize(T obj) throws Exception {
        if(obj ==  null) {
            return new byte[0];
        }
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final Marshaller marshaller = factory.createMarshaller(configuration);
        marshaller.start(Marshalling.createByteOutput(byteArrayOutputStream));
        marshaller.writeObject(obj);
        marshaller.finish();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        return bytes;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws Exception {
        if(data == null) {
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        final Unmarshaller unmarshaller = factory.createUnmarshaller(configuration);
        unmarshaller.start(Marshalling.createByteInput(byteArrayInputStream));
        Object object = unmarshaller.readObject();
        unmarshaller.finish();
        return (T)object;
    }
}
